const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const jwt = require('jsonwebtoken')

const app = express()
// 添加跨域
const cors = require('cors')
app.use(cors())

app.use(express.json())
app.use(express.urlencoded({ extended: false }))

const {router: loginRouter, userList} = require('./login/login')
const getUserListRouter = require('./login/getUserList')
const uploadRouter = require('./login/upload')


const { expressjwt: expressJWT } = require('express-jwt')
app.use(expressJWT({secret:'login', algorithms: ['HS256']}).unless({path:[/^\/api/, /^\/uploads/]}))
app.use((err,req,res,next)=>{
    if(err.name==='UnauthorizedError')return res.send({status:1,message:'身份认证失败！'})

})

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
    next()
  })
// 静态文件服务
app.use('/uploads', express.static('uploads'))
app.use('/api', loginRouter)
app.use('/my', getUserListRouter)
app.use('/api', uploadRouter)

const httpServer = createServer(app)
const io = new Server(httpServer,{
    cors:{
        origin:'http://localhost:5173'
    },
    pingTimeout:60000,
    pingInterval:25000
})

// 设置一个数组用来记录登录的用户
// const { userList } = loginRouter 
io.use((socket, next) => {
    try{
        const page = socket.handshake.query.page || socket.handshake.auth?.page
        let token = socket.handshake.auth?.token || socket.handshake.query.token

        if(page !== 'chat'){
            throw new Error('非chat页面无法连接')
        }
        if(!token){
            throw new Error('缺少token')
        }
        token = String(token).replace(/^Bearer\s+/i, '')

        const decoded = jwt.verify(token, 'login')
        socket.user = decoded
        next()
    }catch(err){
        next(new Error('连接失败: ' + err.message))
    }
})


io.on('connection', (socket) => {
    console.log(`${socket.user.username} socket已连接`);
    io.emit('join', `${socket.user.username} 进入了聊天室`)

    io.emit('userList', userList)
    socket.on('sendmessage', data => {
        if(data.type && data.type==='file'){
            console.log('收到了文件');
            
        }
        socket.emit('getmessage', {
            sender:'me',
            content:data.content,
            avatar: socket.user.useravatar,
            filename:data.filename || '',
            filesize:data.filesize || 0,
            type:data.type || 'text'
        })
        socket.broadcast.emit('getmessage', {
            sender:'other',
            content:data.content,
            avatar: socket.user.useravatar,
            filename:data.filename || '',
            filesize:data.filesize || 0,
            type:data.type || 'text'
        })
    })

    socket.on('disconnect', () => {
        io.emit('leave', `${socket.user.username} 离开了聊天室`)
        
    })

})
httpServer.listen(9000, () => {
    console.log('服务已启动，9000端口监听中');
    
})